package com.example.demo.aop.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Aspect
@Service
public class AopConfig {

//    @Around("execution(* com.example.demo.aop.service.ICouponService.pay(..))")
    @Around("execution(* com.example.demo.aop.service.*.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;

        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName() + "()";
        Object[] args = joinPoint.getArgs();

        System.out.println("call start ...");
        long start = System.currentTimeMillis();

        result = joinPoint.proceed();  // 调用方法的响应结果，异常必须向外抛（影响事务管理）

        long end = System.currentTimeMillis();
        System.out.println("call end ...");
        System.out.println("call " + className+"."+methodName+" method time cost (ms): "+ (end - start));
        System.out.println("call method args===" + Arrays.toString(args));
        System.out.println("call method return===" + result);

        return result;
    }

    @Before("execution(* com.example.demo.aop.service.ICouponService.pay())")
    public Object beforePayPerformance(){
        Object result = null;

//        System.out.println("执行方法前执行这个方法");
        System.out.println("Pay method before ...");

        return result;
    }

    @After("execution(* com.example.demo.aop.service.ICouponService.pay())")
    public Object afterPayPerformance(){
        Object result = null;

//        System.out.println("执行方法后执行这个方法");
        System.out.println("Pay method after ...");

        return result;
    }

//    @AfterReturning("execution(* com.example.demo.service.ICouponService.pay())")
    @AfterReturning("execution(* com.example.demo.aop.service.ICouponService.*(..))")
    public Object afterReturningPayPerformance(){
        Object result = null;

        System.out.println("Pay method AfterReturning ...");

        return result;
    }
}
